package my.p2p.udp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author fengbo
 */
public class EchoServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private InetSocketAddress addr1;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        ByteBuf buf = packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String str = new String(req, StandardCharsets.UTF_8);
        if("wait".equalsIgnoreCase(str)){
            addr1 = packet.sender();
        }else if("conn".equalsIgnoreCase(str)){
            InetSocketAddress addr2 = packet.sender();
            String remot = "ok::" + addr2.getHostString() + "::" + addr2.getPort();
            ctx.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(remot.getBytes()), addr1));

            remot = "ok::" + addr1.getHostString() + "::" + addr1.getPort();
            ctx.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(remot.getBytes()), addr2));
        }

    }
}